package vn.cuhanh.dialog;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;

import vn.cuhanh.BaseActivity;
import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.bean.AwardHistory;
import vn.cuhanh.fragment.MenuFragment;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.ViewHelper;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class AwardHistoryActivity extends BaseActivity {
	public static ArrayList<AwardHistory> listAwardHistory;
	public static int currentPage = 0;
	private AwardHitoryListAdapter adapter;
	private View noNetwork;
	private View loadingScreen;
	private View noData;
	private View contentWrapper;
	private PullToRefreshListView listView;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.award_history);
		setBehindContentView(R.layout.menu_frame);MenuFragment menuFragment = MenuFragment.getInstance(this);
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, menuFragment).commit();
		
		listView = (PullToRefreshListView)findViewById(R.id.award_history_list);
		adapter = new AwardHitoryListAdapter(this, R.id.award_content_wrapper);
		listView.setAdapter(adapter);
		listView.setMode(Mode.BOTH);
		listView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				loadData(currentPage + 1);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				loadData(currentPage + 1);
			}
		});
		
		noNetwork = findViewById(R.id.award_no_network);
		loadingScreen = findViewById(R.id.char_info_loading);
		noData = findViewById(R.id.award_no_history);
		contentWrapper = findViewById(R.id.content_wrapper);
		OnClickListener reloadListener = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadData(1);
			}
		};
		noData.setOnClickListener(reloadListener);
		noNetwork.setOnClickListener(reloadListener);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		BaseActivity.updateDndScore(findViewById(R.id.footer));
		loadData(1);
	}
	
	@Override
	public boolean isShowBackBtn() {
		return true;
	}
	
	public void showNoNetwork() {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				contentWrapper.setVisibility(View.GONE);
				noNetwork.setVisibility(View.VISIBLE);
				noData.setVisibility(View.GONE);
				loadingScreen.setVisibility(View.GONE);
			}
		});
	}
	
	public void showLoadingScreen() {
		ViewHelper.initLoadingFrame(this, loadingScreen);
		contentWrapper.setVisibility(View.GONE);
		noNetwork.setVisibility(View.GONE);
		noData.setVisibility(View.GONE);
		loadingScreen.setVisibility(View.VISIBLE);
	}
	
	public void showNoData() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				contentWrapper.setVisibility(View.GONE);
				noNetwork.setVisibility(View.GONE);
				noData.setVisibility(View.VISIBLE);
				loadingScreen.setVisibility(View.GONE);
			}
		});
	}
	
	public void showContent() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				contentWrapper.setVisibility(View.VISIBLE);
				noNetwork.setVisibility(View.GONE);
				noData.setVisibility(View.GONE);
				loadingScreen.setVisibility(View.GONE);
			}
		});
	}
	
	public void onRefreshComplete() {
		if(listView != null) {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					listView.onRefreshComplete();
				}
			});
		}
	}
	
	public void loadData(final int page) {
		if(listAwardHistory != null && page <= currentPage) {
			showContent();
			adapter.notifyDataSetChanged();
			onRefreshComplete();
			return;
		}
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String res = HelperFunc.getDataFromSv(getResources().getString(R.string.getAwardHistoryUrl)
							.replace("user_name", MainActivity.username).replace("page_no", String.valueOf(page)));
				onRefreshComplete();
				if(res == null) {
					if(listAwardHistory != null) {
						if(listAwardHistory.size() == 0) {
							showNoData();
						} else {
							showContent();
						}
						return;
					}
					showNoNetwork();
					return;
				}
				try {
					JSONObject jsonRes = new JSONObject(res);
					int result = jsonRes.getInt("result");
					if(result == 1) {
						currentPage = page;
						JSONArray historyData = jsonRes.getJSONArray("historyData");
						if(historyData.length() == 0) {
							if(listAwardHistory == null || listAwardHistory.size() == 0) {
								showNoData();
							}
							showContent();
							return;
						}
						if(listAwardHistory == null) {
							listAwardHistory = new ArrayList<AwardHistory>();
						}
						for(int i = 0; i < historyData.length(); i++) {
							JSONObject obj = historyData.getJSONObject(i);
							listAwardHistory.add(new AwardHistory(
									obj.getString("date"), 
									obj.getString("time"), 
									obj.getString("name"), 
									obj.getInt("status")));
						}
						showContent();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					HelperFunc.readStackTrace(e);
					showNoData();
				}
			}
		});
		showLoadingScreen();
		thread.start();
	}
	
	private class AwardHitoryListAdapter extends ArrayAdapter<AwardHistory> {

		public AwardHitoryListAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}
		
		public int getCount() {
			if(listAwardHistory != null) {
				return listAwardHistory.size();
			}
			return 0;
		}
		
		public View getView(int position, View v, ViewGroup container) {
			if(v == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.award_history_list_item, null);
			}
			AwardHistory obj = listAwardHistory.get(position);
			if(obj == null) {
				return v;
			}
			if(position % 2 == 1) {
				v.setBackgroundColor(0xFFF9F9F9);
			} else {
				v.setBackgroundColor(0xFFFFFFFF);
			}
			TextView date = (TextView)v.findViewById(R.id.award_history_list_item_date);
			date.setText(obj.getDate());
			TextView time = (TextView)v.findViewById(R.id.award_history_list_item_time);
			time.setText(obj.getTime());
			TextView name = (TextView)v.findViewById(R.id.award_history_list_item_name);
			name.setText(obj.getName());
			TextView status = (TextView)v.findViewById(R.id.award_history_list_item_status_text);
			ImageView image = (ImageView)v.findViewById(R.id.award_history_list_item_status_image);
			if(obj.getStatus() == AwardHistory.STATUS_SUCCESS) {
				image.setImageResource(R.drawable.icon_ok);
				status.setText(R.string.success);
			} else {
				image.setImageResource(R.drawable.icon_fail);
				status.setText(R.string.fail);
			}
			return v;
		}
	}
}
